package com.n5x.controller.admin.user;

import com.github.pagehelper.PageHelper;
import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.base.TokenModel;
import com.n5x.common.util.StringUtil;
import com.n5x.controller.BaseController;
import com.n5x.model.admin.AdminUser;
import com.n5x.model.user.*;
import com.n5x.service.IAdminService;
import com.n5x.service.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller("adminUserInfo")
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IAdminService IAdminService;

    @ResponseBody
    @RequestMapping(value = "/getUserInfo")
    public JsonModel info(@RequestParam(value = "phone", required = false) String phone) {
        try {
            if (StringUtil.isBlank(phone)) {
                return getResultError(ResponseCode.Common_ParamError, "缺少参数:phone");
            }
            logger.info("[查询用户信息]phone:{}", new Object[]{phone});
            List<UserInfo> userInfos = iUserService.findUserInfoByPhone(phone);
            if (CollectionUtils.isEmpty(userInfos))
                return getResultError(ResponseCode.Common_DataNotFound, "用户不存在");
            if (userInfos.size() > 1)
                return getResultError(ResponseCode.Common_ParamError, "存在多个用户");
            UserInfo userInfo = userInfos.iterator().next();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("username", userInfo.getName());
            map.put("balance", userInfo.getBalance());
            map.put("userLevel", userInfo.getFkLevel());
            map.put("address", userInfo.getAddress());
            map.put("recommend", userInfo.getRecommend());
            return getResult(map);
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/list")
    public JsonModel info() {
        try {
            String id = request.getParameter("id");
            String username = request.getParameter("username");
            String userLevel = request.getParameter("userLevel");
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("pageSize");
            logger.info("[查询用户列表信息]id:{},username:{},userLevel:{}", new Object[]{id, username, userLevel});
            UserInfoExample.Criteria criteria = new UserInfoExample().createCriteria();
            if (StringUtils.isNotBlank(id)) {
                criteria.andIdEqualTo(id);
            }
            if (StringUtils.isNotBlank(username)) {
                criteria.andNameLike(String.format("%s%s%s", "%", username, "%"));
            }
            if (StringUtils.isNotBlank(userLevel)) {
                String[] userLeves = userLevel.split(",");
                criteria.andFkLevelIn(Arrays.asList(userLeves));
            }
            int count = iUserService.countUserInfoAll(criteria);
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            }
            List<UserInfo> userInfos = iUserService.findUserInfoAll(criteria);
            if (CollectionUtils.isEmpty(userInfos))
                return getResultError(ResponseCode.Common_DataNotFound, "列表为空");
            return getResult(userInfos).setResult(String.valueOf(count));
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/saveUserInfo")
    public JsonModel save() {
        try {
            String username = request.getParameter("username");
            String userLevel = request.getParameter("userLevel");
            String address = request.getParameter("address");
            String balance = request.getParameter("balance");
            UserInfo userInfo = null;
            if (StringUtil.isNotEmptyBlank(username)) {
                userInfo = iUserService.findUserInfoByLogin(username);
            }
            logger.info("[保存用户信息]username:{},userLevel:{},address:{},balance:{}", new Object[]{username, userLevel, address, balance});
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName(username);
                userInfo.setPhone(username);
                UserAccount account = new UserAccount().setLoginName(username).setPassword("111111").setType(UserAccount.AccountType.手机号码.name());
                userInfo.setFkLevel(userLevel);
                userInfo.setAddress(address);
                userInfo.setBalance(new BigDecimal(balance));
                iUserService.saveUserInfoAndAccount(userInfo, account);
            } else {
                userInfo.setFkLevel(userLevel);
                userInfo.setAddress(address);
                userInfo.setBalance(new BigDecimal(balance));
                iUserService.saveUserInfo(userInfo);
            }
            return getResult(userInfo.getId());
        } catch (Exception e) {
            logger.error("[保存用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    /**
     * 后台操作用户充值
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/renewal")
    public JsonModel renewal() {
        try {
            String userId = request.getParameter("userId");
            String moneyStr = request.getParameter("money");
            BigDecimal money = new BigDecimal(moneyStr);
            UserInfo userInfo = iUserService.findUserInfo(userId);
            String token = request.getParameter("token");
            TokenModel tokenModel = getTokenModelByToken(token);
            String adminUserId = tokenModel.getUserId();
            AdminUser adminUser = IAdminService.findAdminUser(adminUserId);
            if (userInfo == null) {
                return getResult(ResponseCode.Common_ParamError, "用户为空");
            }
            if (money.compareTo(BigDecimal.ZERO) == -1) {
                return getResult(ResponseCode.Common_ParamError, "充值金额不能少于0");
            }
            logger.info("[{}]id:{},phone:{},balance{}", new Object[]{"用户充值信息", userId, userInfo.getPhone(), money});
            UserTransactionRecord extUserTransactionRecord = null;
            if (money.compareTo(new BigDecimal(1000)) == 0) {
                //充1000送100
                money = money.add(new BigDecimal(100));
                extUserTransactionRecord = new UserTransactionRecord(userId, adminUserId, UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(100));
                extUserTransactionRecord.setDisable(Boolean.FALSE);
            } else if (money.compareTo(new BigDecimal(500)) == 0) {
                //充500送20
                money = money.add(new BigDecimal(20));
                extUserTransactionRecord = new UserTransactionRecord(userId, adminUserId, UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(20));
                extUserTransactionRecord.setDisable(Boolean.FALSE);
            } else if (money.compareTo(new BigDecimal(300)) == 0) {
                //充300送5
                money = money.add(new BigDecimal(5));
                extUserTransactionRecord = new UserTransactionRecord(userId, adminUserId, UserTransactionRecord.Method.微信, UserTransactionRecord.TransactionType.赠送, new BigDecimal(5));
                extUserTransactionRecord.setDisable(Boolean.FALSE);
            }
            userInfo.setBalance(userInfo.getBalance().add(money));
            userInfo.setFkLevel("1");
            UserTransactionRecord userTransactionRecord = new UserTransactionRecord(userInfo.getId(), adminUser.getFullName(), UserTransactionRecord.Method.现金, UserTransactionRecord.TransactionType.充值, money);
            userTransactionRecord.setDisable(Boolean.FALSE);
            iUserService.saveUserTransactionRecord(userTransactionRecord, userInfo, extUserTransactionRecord);
            return getResult(userInfo.getId());
        } catch (Exception e) {
            logger.error("[保存用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/transactionRecord/list")
    public JsonModel findTransactionRecord() {
        try {
            String token = request.getParameter("token");
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            String id = request.getParameter("id");
            String transactionNumber = request.getParameter("transactionNumber");
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("pageSize");
            UserTransactionRecordExample.Criteria criteria = new UserTransactionRecordExample().createCriteria();
            if (StringUtils.isNotBlank(id)) {
                criteria.andIdEqualTo(id);
            }
            if (StringUtils.isNotBlank(userId)) {
                criteria.andFkUserEqualTo(userId);
            }
            if (StringUtils.isNotBlank(transactionNumber)) {
                criteria.andTransactionNumberLike(String.format("%s%s%s", "%", transactionNumber, "%"));
            }
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            }
            List<UserTransactionRecord> list = iUserService.findUserTransactionRecordAll(criteria);
            if (CollectionUtils.isEmpty(list))
                return getResult(ResponseCode.Common_DataNotFound, "充值记录列表为空");
            return getResult(list);
        } catch (Exception e) {
            logger.error("[查询用户信息失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }
}